package hippo.utils;

import hippo.exceptions.ObjectCopyFailedException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public final class Utilities {

	private Utilities() {}
	
	public static Object copyObject(Object o) throws ObjectCopyFailedException {
		try {
		// ObjectOutputStream erzeugen
		ByteArrayOutputStream bufOutStream = new ByteArrayOutputStream();
		ObjectOutputStream outStream = new ObjectOutputStream(bufOutStream);

		// Objekt im byte-Array speichern
		outStream.writeObject(o);
		outStream.close();

		// Pufferinhalt abrufen
		byte[] buffer = bufOutStream.toByteArray();
		// ObjectInputStream erzeugen
		ByteArrayInputStream bufInStream = new ByteArrayInputStream(buffer);
		ObjectInputStream inStream = new ObjectInputStream(bufInStream);
		// Objekt wieder auslesen
		Object newO = inStream.readObject();
		return newO;
		} catch (IOException e) {
			e.printStackTrace();
			throw new hippo.exceptions.ObjectCopyFailedException("I/O Error", e);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new hippo.exceptions.ObjectCopyFailedException("Class not found", e);
		}
	}
}
